package com.yuexia.yxim.server.server;

import com.yuexia.yxim.common.code.ProtobufDecoder;
import com.yuexia.yxim.server.handler.ChatRedirectHandler;
import com.yuexia.yxim.server.handler.HeartBeatServerHandler;
import com.yuexia.yxim.server.handler.LoginRequestHandler;
import com.yuexia.yxim.server.handler.ServerExceptionHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.rmi.ServerException;

/**
 * @Author: yue_xia
 * @Date: 2020/6/2 8:43 下午
 */
@Slf4j
@Service
public class ChatServer {

    @Value("${server.port}")
    private int port;

    @Autowired
    private LoginRequestHandler loginRequestHandler;

    @Autowired
    private ServerExceptionHandler serverExceptionHandler;

    @Autowired
    private ChatRedirectHandler chatRedirectHandler;

    //事件循环组
    private EventLoopGroup bossGroup = new NioEventLoopGroup();
    private EventLoopGroup workGroup = new NioEventLoopGroup();

    //启动器
    private ServerBootstrap bootstrap = new ServerBootstrap();

    public void run() {

        try {
            //reactor 线程
            bootstrap.group(bossGroup, workGroup)
                    //设置为nio类型的channel
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pip = socketChannel.pipeline();
                            pip.addLast(new ProtobufDecoder());
                            pip.addLast(new ProtobufEncoder());
                            pip.addLast(new HeartBeatServerHandler());

                            //添加用来登录的处理器，登录后删除
                            pip.addLast(loginRequestHandler);
                            pip.addLast(chatRedirectHandler);
                            pip.addLast(serverExceptionHandler);
                        }
                    });

            //开始绑定server
            ChannelFuture channelFuture = bootstrap.bind().sync();
            log.info("服务器启动，端口 {}", channelFuture.channel().localAddress());

            //监听通道关闭
            ChannelFuture closeFuture = channelFuture.channel().closeFuture();
            closeFuture.sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }

    }
}
